package net.basshista.jsshtunneling.jsch;

import java.beans.XMLEncoder;
import java.util.ArrayList;
import java.util.List;

import net.basshista.jsshtunneling.beans.TunnelBean;
import net.basshista.jsshtunneling.beans.TunnelBean.TunnelType;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHConnection {

    private JSch jSch;
    private List<Session> sessions;

    private List<TunnelBean> tunnels;

    public SSHConnection() {
    }

    public SSHConnection(List<TunnelBean> tunnels) throws JSchException {
	this.tunnels = tunnels;
	jSch = new JSch();
	sessions = new ArrayList<Session>();

	for (TunnelBean tunnel : tunnels) {
	    Session session = jSch.getSession(tunnel.getHostBean().getUser(), tunnel.getHostBean().getHost());
	    session.setUserInfo(tunnel.getHostBean());

	    if (tunnel.getTunnelType() == TunnelType.Local)
		session.setPortForwardingL(tunnel.getLocalPort(), tunnel.getRemoteHost(), tunnel.getRemotePort());
	    else
		session.setPortForwardingR(tunnel.getLocalPort(), tunnel.getRemoteHost(), tunnel.getRemotePort());
	    sessions.add(session);
	}

    }

    public void connect() throws JSchException {
	for (Session session : sessions) {
	    session.connect();
	}
    }

    public void disconnect() {
	for (Session session : sessions) {
	    session.disconnect();
	}
    }

}